package com.kanshu.basictest.sys.permission;

import android.app.Activity;
import android.content.pm.PackageManager;

public class PermissionHelper {

    private Activity mActivity;
    private PermissionCallback mPermissionCallback;
    private int mRequestCode;

    public PermissionHelper(Activity activity, int requestCode, PermissionCallback pi) {
        mActivity = activity;
        mRequestCode = requestCode;
        mPermissionCallback = pi;
    }


    /**
     * 开始请求权限。
     * 方法内部已经对Android M 或以上版本进行了判断，外部使用不再需要重复判断。
     * 如果设备还不是M或以上版本，则也会回调到requestPermissionsSuccess方法。
     */
    public void requestPermissions(String[] permissions) {
        //获取尚未授权的权限
        String[] deniedPermissions = PermissionUtil.getDeniedPermissions(mActivity.getApplicationContext(), permissions);
        if (deniedPermissions != null && deniedPermissions.length > 0) {
            PermissionUtil.requestPermissions(mActivity, deniedPermissions, mRequestCode);
        } else {
            mPermissionCallback.onRequestPermissionSuccess();
        }
    }


    /**
     * @param requestCode 请求码
     * @param permissions 请求过的权限
     * @param grantResult 权限的状态
     * @return
     */
    public boolean handlePermissionResult(int requestCode, String[] permissions, int[] grantResult) {

        if (requestCode == mRequestCode) {

            boolean isAllGranted = true;
            for (int result : grantResult) {
                if (result == PackageManager.PERMISSION_DENIED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                mPermissionCallback.onRequestPermissionSuccess();
            } else {
                mPermissionCallback.onRequestPermissionFail();
            }

            return true;

        }
        return false;

    }


}

